package com.ruoyi.prod.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.prod.es.EsProd;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import com.ruoyi.prod.mapper.TbProdMapper;
import com.ruoyi.prod.domain.TbProd;
import com.ruoyi.prod.service.ITbProdService;

/**
 * 商品Service业务层处理
 * 
 * @author yyj
 * @date 2025-08-08
 */
@Service
public class TbProdServiceImpl implements ITbProdService 
{
    @Autowired
    private TbProdMapper tbProdMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    /**
     * 查询商品
     * 
     * @param prodId 商品主键
     * @return 商品
     */
    @Override
    public TbProd selectTbProdByProdId(Long prodId)
    {
        return tbProdMapper.selectTbProdByProdId(prodId);
    }

    /**
     * 查询商品列表
     * 
     * @param tbProd 商品
     * @return 商品
     */
    @Override
    public List<TbProd> selectTbProdList(TbProd tbProd)
    {
        return tbProdMapper.selectTbProdList(tbProd);
    }

    /**
     * 新增商品
     * 
     * @param tbProd 商品
     * @return 结果
     */
    @Override
    public int insertTbProd(TbProd tbProd)
    {
        tbProd.setCreateTime(DateUtils.getNowDate());
        return tbProdMapper.insertTbProd(tbProd);
    }

    /**
     * 修改商品
     * 
     * @param tbProd 商品
     * @return 结果
     */
    @Override
    public int updateTbProd(TbProd tbProd)
    {
        tbProd.setUpdateTime(DateUtils.getNowDate());
        return tbProdMapper.updateTbProd(tbProd);
    }

    /**
     * 批量删除商品
     * 
     * @param prodIds 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdIds(Long[] prodIds)
    {
        return tbProdMapper.deleteTbProdByProdIds(prodIds);
    }

    /**
     * 删除商品信息
     * 
     * @param prodId 商品主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdId(Long prodId)
    {
        return tbProdMapper.deleteTbProdByProdId(prodId);
    }

    @Override
    public AjaxResult createIndex() {

        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOperations.exists();
        if(exists){
            indexOperations.delete();
        }
            indexOperations.create();
        Document mapping = indexOperations.createMapping();
        indexOperations.putMapping(mapping);
        return AjaxResult.success("创建索引成功");
    }

    @Override
    public AjaxResult synMysql() {

        List<TbProd> tbProds = tbProdMapper.selectTbProdList(new TbProd());

        for (TbProd prod : tbProds) {
            EsProd esProd = BeanUtil.toBean(prod, EsProd.class);

            elasticsearchRestTemplate.save(esProd);
        }
        return AjaxResult.success("同步成功");
    }

    @Override
    public TableDataInfo ProdListFromEs(EsProd esProd,Integer pageNum,Integer pageSize) {

        Integer form=0;
        if(pageNum>0){
            form=pageNum-1;
        }

        PageRequest pageRequest = PageRequest.of(form, pageSize);
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if(StringUtils.isNotEmpty(esProd.getProdName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("prodName",esProd.getProdName()));
        }

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("prodName").preTags("<font color='red'>").postTags("</font>");

        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("prodId");

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(pageRequest).withHighlightBuilder(highlightBuilder).withSorts(sortBuilder);
        SearchHits<EsProd> searchHits = elasticsearchRestTemplate.search(builder.build(), EsProd.class);

        ArrayList<EsProd> list = new ArrayList<>();
        long totalHits = searchHits.getTotalHits();

        searchHits.getSearchHits().stream().forEach(item->{
            EsProd content = item.getContent();

            List<String> prodNameList = item.getHighlightField("prodName");
            if(StringUtils.isNotEmpty(prodNameList)){
                content.setProdName(prodNameList.get(0));
            }
            list.add(content);

        });
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("es列表展示成功");
        tableDataInfo.setRows(list);
        tableDataInfo.setTotal(totalHits);

        return tableDataInfo;
    }
}
